//
//  SMRTAgencyViewController.m
//  SMRTv1
//
//  Created by Ding on 8/12/13.
//  Copyright (c) 2013 Trans-Intelligence. All rights reserved.
//

#import "SMRTAgencyViewController.h"

@interface SMRTAgencyViewController ()

@end

@implementation SMRTAgencyViewController
@synthesize  sections=_sections;
@synthesize agencyNameSection=_agencyNameSection;
@synthesize subSystemListSection=_subSystemListSection;
@synthesize subSystemList=_subSystemList;
@synthesize addSubSystemButton=_addSubSystemButton;
@synthesize publicSender=_publicSender;
@synthesize agency=_agency;
@synthesize agencyNameTextView=_agencyNameTextView;
@synthesize syncTimeSection=_syncTimeSection;
@synthesize gestureRecognizer=_gestureRecognizer;
//@synthesize timePicker=_timePicker;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id) initWithNibNameAndAgency:(NSString *)nibName agency:(Agency *)agency bundle:(NSBundle *)nibBundle
{
    self=[super initWithNibName:nibName bundle:nibBundle];
    self.agency=agency;
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_agencyNameSection release];
    [_subSystemListSection release];
    [_subSystemList release];
    [_addSubSystemButton release];
    [_agency release];
    [_agencyNameTextView release];
    [_gestureRecognizer release];
//    [_timePicker release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    
    if(!_agencyNameSection)
    {
        _agencyNameSection=[[TableSection alloc]init];
        _agencyNameSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_agencyNameSection.contents addObject:self.agency.agencyName];        
        _agencyNameSection.header=@"Agency Name";
    }
    if(!_syncTimeSection)
    {
        _syncTimeSection=[[TableSection alloc]init];
        _syncTimeSection.contents=[[[NSMutableArray alloc] init] autorelease];
        NSString * syncTimeString=self.agency.syncTime;
        if ([syncTimeString isEqualToString:@""]||syncTimeString==nil) {
            syncTimeString=@"Click to set sync time";
        }
        [_syncTimeSection.contents addObject:syncTimeString];        
        _syncTimeSection.header=@"Sync Time";
    }
    if(!_subSystemListSection)
    {
        _subSystemListSection=[[TableSection alloc]init];
        self.subSystemList=[XMLParser getSubSystemListofAgency:self.agency];
        _subSystemListSection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.subSystemList.count; i++) {
            [_subSystemListSection.contents addObject:[[self.subSystemList objectAtIndex:i] subSystemName]];
        }
        
        _subSystemListSection.header=@"SubSystem List";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:self.agencyNameSection];
        [_sections addObject:self.syncTimeSection];
        [_sections addObject:self.subSystemListSection];
    }
    
    
    //add gesture recognization
    if (!_gestureRecognizer) {
        _gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewReturn:)] ;
        self.gestureRecognizer.cancelsTouchesInView = NO;
        [self.tableView addGestureRecognizer:self.gestureRecognizer];
    }

    
    //config tool bar buttons and hidden status
    [self.navigationController setToolbarHidden:NO];
    CustomizedBarButtonItem *homeButtonItem=[[[CustomizedBarButtonItem alloc] initCustomizedBarButtonItem:[UIImage imageNamed:@"home.png"] target:self action:@selector(goToHome:)] autorelease];
    self.toolbarItems = [ NSArray arrayWithObjects: homeButtonItem,nil ];
}

- (void)viewWillAppear:(BOOL)animated
{
    //    [self.navigationController setToolbarHidden:YES];
    [self setTitle:@"Agency"];
    [self.navigationController setNavigationBarHidden:NO];
    [self updateViewController];
}

- (void) updateViewController
{
    if(self.syncTimeSection)
    {
        
        [self.syncTimeSection.contents removeAllObjects];
        NSString * syncTimeString=self.agency.syncTime;
        if ([syncTimeString isEqualToString:@""]||syncTimeString==nil) {
            syncTimeString=@"Click to set sync time";
        }
        [self.syncTimeSection.contents addObject:syncTimeString];
    }
    self.subSystemList=[XMLParser getSubSystemListofAgency:self.agency];
    
    [self.subSystemListSection.contents removeAllObjects];
    for (int i=0; i<self.subSystemList.count; i++) {
        [self.subSystemListSection.contents addObject:[[self.subSystemList objectAtIndex:i] subSystemName]];
    }
    [self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.agency.agencyName=self.agencyNameTextView.text;
    [XMLParser updateAgency:self.agency];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=NSLineBreakByWordWrapping;
    cell.textLabel.text=sectionContentString;
    
    switch (indexPath.section) {
        case 0:
        {
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            CGFloat height=[TableSection calculateStringHeight:[[section contents] objectAtIndex:indexPath.row]];
            self.agencyNameTextView=[[[UITextView alloc] initWithFrame:CGRectMake(1, 5, (CONST_portraitCellWidth-2), (height-10))] autorelease];
            [self.agencyNameTextView setText:sectionContentString];
            [self.agencyNameTextView setFont:[TableSection TitleFont]];
            self.agencyNameTextView.delegate=self;
            
            [[cell contentView] addSubview:self.agencyNameTextView];
            [cell setBackgroundColor:[TableSection WhiteColor]];
            
            return cell;
        }
            
            break;
        case 1:
        {
            
        }
            break;
            
        default:
            cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
            break;
    }
    
    
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = NSTextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkGrayColor];
    
    
    [headerView addSubview:aLabel];
    switch (section) {
        case 0:
        case 1:
        {
            return headerView;
        }
            break;
            
        case 2:
        {
            UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
            [newbutton setFrame:CGRectMake(160,4,30,30)];
            [newbutton setTag:(section)];
            [newbutton addTarget:self action:@selector(clickAddSubSystemButton:)
                forControlEvents:UIControlEventTouchUpInside];
            [headerView addSubview:newbutton];
        }
            break;
        default:
        {
            
        }
    }
    return headerView;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return UITableViewCellEditingStyleNone;
    }
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Commit the delete
        [self removeSubSystem:indexPath.row];
        
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    
    return [[self.sections objectAtIndex:section] header];
    
}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //yes
        int tag=self.publicSender;
        [XMLParser removeSubSystem:[self.subSystemList objectAtIndex:tag]];
        [self updateViewController];
        
    } else {
        
    }
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 1:
        {
            SMRTSyncTimePickerViewController *timePickerView=[[[SMRTSyncTimePickerViewController alloc] initWithAgency:self.agency nibNameOrNil:@"SMRTSyncTimePickerViewController" bundle:nil] autorelease];
            [timePickerView setTitle:@"Select Sync Time"];
            [self setTitle:@"Cancel"];
            [self.navigationController pushViewController:timePickerView animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
        case 2:
        {
            SMRTSubSystemViewController *subSystemController=[[[SMRTSubSystemViewController alloc] initWithNibNameAndSubSystem:@"SMRTSubSystemViewController" subSystem:[self.subSystemList objectAtIndex:indexPath.row] bundle:nil] autorelease];
            [subSystemController setTitle:@"SubSystem"];
            [self.navigationController pushViewController:subSystemController animated:YES];
            [self.navigationController setNavigationBarHidden:NO animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark -TextView Delegate
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
//    self.gestureRecognizer.cancelsTouchesInView=NO;
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    self.agency.agencyName=textView.text;
    [XMLParser updateAgency:self.agency];
    [self.agencyNameSection.contents removeAllObjects];
    [self.agencyNameSection.contents addObject:self.agency.agencyName];    
    self.agencyNameSection.header=@"Agency Name";
//    self.gestureRecognizer.cancelsTouchesInView=YES;
    return YES;
}

#pragma mark - Customized functions
- (void) clickAddSubSystemButton:(id)sender
{
    SubSystem *subSystem=[[[SubSystem alloc] init] autorelease];
    [subSystem setSubSystemID:[XMLParser createSubSystemID:self.agency]];
    [subSystem setParentAgencyID:self.agency.agencyID];
    [subSystem setSubSystemName:@"New SubSystem"];
    [XMLParser createSubSystem:subSystem];
    [self updateViewController];
}




- (void) removeSubSystem: (int)row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation"
                                                    message:@"Delete the SubSystem and its signals?"
                                                   delegate:self
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}

- (IBAction)textViewReturn:(id)sender
{
    [self.agencyNameTextView resignFirstResponder];
}

- (void) goToHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
